<template>
  <div class="avatar-upload">
    <div class="avatar-preview" @click="triggerUpload">
      <img 
        v-if="avatarUrl" 
        :src="avatarUrl" 
        alt="头像"
        class="avatar-image"
      />
      <div v-else class="avatar-placeholder">
        {{ placeholder }}
      </div>
      <div class="upload-mask">
        <span class="upload-icon">📷</span>
        <span class="upload-text">{{ uploadText }}</span>
      </div>
    </div>
    <input 
      ref="fileInput"
      type="file" 
      accept="image/jpeg,image/jpg,image/png,image/gif"
      @change="handleFileChange"
      style="display: none"
    />
    
    <!-- 裁剪弹窗 -->
    <div v-if="showCropModal" class="crop-modal" @click.self="closeCropModal">
      <div class="crop-container">
        <div class="crop-header">
          <h3>裁剪头像</h3>
          <button class="close-btn" @click="closeCropModal">×</button>
        </div>
        <div class="crop-body">
          <div class="crop-preview">
            <img ref="cropImage" :src="tempImageUrl" alt="待裁剪图片" />
          </div>
        </div>
        <div class="crop-footer">
          <button class="btn btn-cancel" @click="closeCropModal">取消</button>
          <button class="btn btn-primary" @click="confirmCrop" :disabled="uploading">
            {{ uploading ? '上传中...' : '确认上传' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '头'
  },
  uploadText: {
    type: String,
    default: '修改头像'
  },
  maxSize: {
    type: Number,
    default: 5 * 1024 * 1024 // 5MB
  }
})

const emit = defineEmits(['update:modelValue', 'upload'])

const fileInput = ref(null)
const avatarUrl = ref(props.modelValue)
const showCropModal = ref(false)
const tempImageUrl = ref('')
const selectedFile = ref(null)
const uploading = ref(false)

watch(() => props.modelValue, (newVal) => {
  avatarUrl.value = newVal
})

function triggerUpload() {
  fileInput.value.click()
}

function handleFileChange(event) {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件')
    return
  }

  // 验证文件大小
  if (file.size > props.maxSize) {
    alert(`图片大小不能超过 ${props.maxSize / 1024 / 1024}MB`)
    return
  }

  selectedFile.value = file

  // 读取图片预览
  const reader = new FileReader()
  reader.onload = (e) => {
    tempImageUrl.value = e.target.result
    showCropModal.value = true
  }
  reader.readAsDataURL(file)

  // 清空input，允许重复选择同一文件
  event.target.value = ''
}

function closeCropModal() {
  showCropModal.value = false
  tempImageUrl.value = ''
  selectedFile.value = null
}

async function confirmCrop() {
  if (!selectedFile.value) return

  uploading.value = true

  try {
    // 创建 FormData
    const formData = new FormData()
    formData.append('file', selectedFile.value)

    // 触发上传事件，由父组件处理实际上传逻辑
    emit('upload', formData, (url) => {
      avatarUrl.value = url
      emit('update:modelValue', url)
      closeCropModal()
      uploading.value = false
    })
  } catch (error) {
    console.error('上传失败:', error)
    alert('上传失败，请重试')
    uploading.value = false
  }
}
</script>

<style scoped lang="scss">
.avatar-upload {
  display: inline-block;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  
  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .avatar-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 36px;
    font-weight: bold;
  }
  
  .upload-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
    
    .upload-icon {
      font-size: 24px;
      margin-bottom: 4px;
    }
    
    .upload-text {
      font-size: 12px;
      color: white;
    }
  }
  
  &:hover .upload-mask {
    opacity: 1;
  }
}

.crop-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.crop-container {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  animation: slideUp 0.3s;
}

@keyframes slideUp {
  from {
    transform: translateY(50px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.crop-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
  
  .close-btn {
    background: none;
    border: none;
    font-size: 32px;
    color: #999;
    cursor: pointer;
    line-height: 1;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: color 0.2s;
    
    &:hover {
      color: #333;
    }
  }
}

.crop-body {
  padding: 24px;
  flex: 1;
  overflow: auto;
  
  .crop-preview {
    display: flex;
    justify-content: center;
    align-items: center;
    
    img {
      max-width: 100%;
      max-height: 400px;
      border-radius: 8px;
    }
  }
}

.crop-footer {
  padding: 16px 24px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn {
  padding: 10px 24px;
  border-radius: 6px;
  border: none;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
    
    &:hover {
      background: #e8e8e8;
    }
  }
  
  &.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    
    &:hover:not(:disabled) {
      opacity: 0.9;
      transform: translateY(-1px);
    }
    
    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
  }
}
</style>

